<template>
    <n-form
        style="margin-top: 12px"
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-placement="left"
        label-width="100"
        require-mark-placement="right-hanging"
        size="medium"
    >
        <n-form-item label="名称" path="name">
            <n-input v-model:value="formData.name" placeholder="请输入名称"/>
        </n-form-item>
        <n-form-item label="VDB数据库" path="vdbResourceId">
            <jb-select  v-model:value="formData.vdbResourceId" url="/VDBResource/listAllEnabledType"
                       labelField="name" valueField="id" :filterable="true"></jb-select>
        </n-form-item>
        <n-form-item label="简介" path="">
            <n-input
                v-model:value="formData.briefInfo"
                type="textarea"
                placeholder="请输入简介"

            />
        </n-form-item>

    </n-form>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import {useMessage} from 'naive-ui'
import {JBoltApi} from '@/service/request'
import {useResetableData} from "@/hooks/common/use-resetable-data.js";


const props = defineProps({
    id: [String, Number],
    appId: [String]
})

const message = useMessage()
const formRef = ref(null)

// 表单数据
const formData = useResetableData({
    name: '',
    briefInfo: '',
    vdbResourceId: null,
    appId: props.appId
})


// 表单验证规则
const rules = {
    vdbResourceId: {
        required: true,
        message: '请选择VDB数据库',
        trigger: 'change'
    },
    briefInfo: {
        required: true,
        message: '请输入问题或内容',
        trigger: 'blur'
    },
    name: {
        required: true,
        message: '请输入名称',
        trigger: 'blur'
    }
}

// 提交方法
const submit = async () => {
        await formRef.value?.validate()
        const api = props.id ? '/aiKnowledgeBase/update' : '/aiKnowledgeBase/add'
        const params = {
            ...formData,
            id: props.id
        }

       let { error, result }  =  await JBoltApi.tryPost(api, params)
        if (error) {
            message.error(error)
            return
        }
        message.success('保存成功')
}

// 加载详情
const loadDetail = async () => {
    if (!props.id) return
        const {result} = await JBoltApi.get(`/aiKnowledgeBase/getById/${props.id}`)
        if(result){
            console.debug('详情:', result.data)
            formData._reset(result.data)
        }

}

onMounted(()=>{
    if(props.id){
        loadDetail()
    }
})

defineExpose({
    submit
})
</script>